package ynu.beggar.server.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import ynu.beggar.server.entities.DO.UserBasicInfoDO;

import java.util.Date;

public class JwtUtils {

    public static final String SUBJECT = "ynubeggar";

    public static final long EXPIRE = 1000 * 60 * 60 * 12;  //过期时间，毫秒

    //秘钥
    public static final String APPSECRET = "cyl0511";

    /**
     * 生成jwt
     *
     * @param userBasicInfoDO
     * @return
     */
    public static String geneJsonWebToken(UserBasicInfoDO userBasicInfoDO) {

        if (userBasicInfoDO == null || userBasicInfoDO.getUserName() == null || userBasicInfoDO.getStuId() == null) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("userId", userBasicInfoDO.getUserId())
                .claim("userName", userBasicInfoDO.getUserName())
                .claim("stuId", userBasicInfoDO.getStuId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
            return claims;

        } catch (Exception e) {
        }
        return null;

    }

}


